/*
 * UpdateController.java
 *
 * Created on March 12, 2007, 3:04 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package Data;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 *
 * @author Danny Beutler
 */
public class UpdateController {
    ///////////////////////////////////////
    ///   Singleton pattern
    
    private static UpdateController instance = null;
    
    /** Creates a new instance of payment */
    private UpdateController() {
    }
    
    public static synchronized UpdateController getInstance() {
        if (instance == null) {
            instance = new UpdateController();
        }
        return instance;
    }
    
    
    public void post_sale(TransactionBO tx) throws DataException{
        Connection conn;
        try {
            conn = ConnectionPool.getInstance().get();
            
            
            TransactionDAO.getInstance().save(tx,conn);
            if(tx.getPayment()!=null){
                PaymentDAO.getInstance().save(tx.getPayment(),conn);
            }
            
            if(tx.getTxLines()!=null){
                List<TransactionLineBO> transactionLines=tx.getTxLines();
                for(int i=0;i<transactionLines.size();i++){
                    System.out.println(tx.getTxLines().get(i).getRevenueSource().getClass().getName());
                    RevenueSourceDAO rsDAO = RevenueSourceFactory.getInstance().getDAO(tx.getTxLines().get(i).getRevenueSource().getClass().getName());
                    RevenueSourceBO rsBO = tx.getTxLines().get(i).getRevenueSource();
                    rsDAO.save(rsBO,conn);
                    TransactionLineDAO.getInstance().save(transactionLines.get(i),conn);
                    if(transactionLines.get(i).getCoupon()!=null){
                        CouponDAO.getInstance().save(transactionLines.get(i).getCoupon(),conn);
                    }
                }
            }
            
            conn.commit();
            ConnectionPool.getInstance().release(conn);
        } catch (ConnectionPoolException ex) {
            ex.printStackTrace();
        } catch (DataException ex) {
            ex.printStackTrace();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
    
    public void post_backup(MemberBO member, TransactionBO trans){
        try {
            MemberDAO.getInstance().save(member);
            post_sale(trans);
        } catch (DataException ex) {
            ex.printStackTrace();
            System.out.println("Post_backup failed.");
        }
    }
    
    
    public void setInstance(UpdateController instance) {
        this.instance = instance;
    }
    
    
}
